# 与帖子相关的ORM模型
from exts import db
from datetime import datetime


# 板块模型
class BoardModel(db.Model):
    __tablename__ = "board"
    __table_args__ = {'comment': '板块表'}
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment="主键id")
    name = db.Column(db.String(30), nullable=False, comment="板块名字")
    create_time = db.Column(db.DateTime, default=datetime.now)
    is_active = db.Column(db.Boolean, default=True)


# 帖子模型
class PostModel(db.Model):
    __tablename__ = "post"
    __table_args__ = {'comment': '帖子表'}
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(200), nullable=False)
    content = db.Column(db.Text, nullable=False)
    create_time = db.Column(db.DateTime, default=datetime.now)
    read_count = db.Column(db.Integer, default=0)
    is_active = db.Column(db.Boolean, default=True)
    # 外键
    board_id = db.Column(db.Integer, db.ForeignKey("board.id"))
    author_id = db.Column(db.String(100), db.ForeignKey("user.id"), nullable=False)

    board = db.relationship("BoardModel", backref="posts")
    author = db.relationship("UserModel", backref="posts")


# 评论模型
class CommentModel(db.Model):
    __tablename__ = "comment"
    __table_args__ = {'comment': '评论表'}
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    content = db.Column(db.Text, nullable=False)
    create_time = db.Column(db.DateTime, default=datetime.now)
    is_active = db.Column(db.Boolean, default=True)
    # 外键
    post_id = db.Column(db.Integer, db.ForeignKey("post.id"))
    author_id = db.Column(db.String(100), db.ForeignKey("user.id"), nullable=False)

    # 自动按照评论发表时间倒序排列 使用lazy="dynamic"参数，这将使post.comments变成AppenderQuery对象，可以使用filer或filer_by
    post = db.relationship("PostModel", backref=db.backref("comments", order_by=create_time.desc(), lazy="dynamic"))
    author = db.relationship("UserModel", backref="comments")
